//
//  UserInfoViewController.m
//  OCPB
//
//  Created by Killerp8ss on 7/4/56 BE.
//  Copyright (c) 2556 Siroj Chongkolwanont. All rights reserved.
//

#import "UserInfoViewController.h"
#import "UserInfo.h"
#import "KeepTrackViewController.h"
#import "ComplainViewController.h"
#import "RegisterViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "ComTypeLv0.h"

@interface UserInfoViewController ()

@end

@implementation UserInfoViewController
@synthesize idNumberText;
@synthesize nameText;
@synthesize telText;
@synthesize emailText;
@synthesize address;
@synthesize authorizationData;
@synthesize scrollView;

NSMutableData* responseData;
UserInfo* userInfo;

NSString* currentType;
NSString* currentL0;

NSMutableArray *comTypeLv0Array;

UIAlertView *mainAlert;
UIAlertView *typeAlert;


id jsonObjectFromUrlString(NSString *urlString);


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (IBAction)backAction:(id)sender {
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"New_Navigation_background_320x46.png"]
                                                  forBarMetrics:UIBarMetricsDefault];
    
    [self.navigationController popViewControllerAnimated:NO];
}


- (IBAction)editAction:(id)sender {
    
    //[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"23Navigation_background_347x46.png"]
                                                 // forBarMetrics:UIBarMetricsDefault];
    
    [self performSegueWithIdentifier:@"ToEditUser" sender:self];
}

- (void)viewDidLoad
{
    [self getUserInfo];
    [super viewDidLoad];
    
    
    
   // scrollView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"pw_maze_white.png"]];
    
    [[address layer] setBorderColor:[[UIColor grayColor] CGColor]];
    [[address layer] setBorderWidth:2.3];
    [[address layer] setCornerRadius:15];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"22Navigation_background_320x46.png"]
                                                  forBarMetrics:UIBarMetricsDefault];
    
    UIButton *button1 = [[UIButton alloc] init];
    button1.frame= CGRectMake(0,0,43,32);
    [button1 setBackgroundImage:[UIImage imageNamed: @"bottom_home.png"] forState:UIControlStateNormal];
    
    [button1 addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button1];
    
    UIButton *button2 = [[UIButton alloc] init];
    button2.frame= CGRectMake(0,0,43,32);
    [button2 setBackgroundImage:[UIImage imageNamed: @"ic_action_content_edit.png"] forState:UIControlStateNormal];
    
    [button2 addTarget:self action:@selector(editAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"n_topic_news1.png"]
      //                                            forBarMetrics:UIBarMetricsDefault];
    
    //self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button2];
    
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)getUserInfo
{
    NSURL *url = [NSURL URLWithString:@"http://www.aitproject.com/demo/webservice/public/service/petitioner"];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    
    [request setHTTPMethod:@"GET"];
    //[request setValue:[self Authorization] forHTTPHeaderField:@"Authorization"];
    //[request setValue:@"OCPB Bny8p47kBs3WnlFceLkhcY9j6x88bsk6:MTIzNDU2Nzg5MDExNDoxMzE0NTkyNTUxOjRhODNiZjJhZTY5ZDZkMjMwMjQ5YWVhY2Q1NTFlOTE4M2E4NzAzYmQ="  forHTTPHeaderField:@"Authorization"];
    NSLog(@"authorizationData is %@", authorizationData);
    
    [request setValue:authorizationData  forHTTPHeaderField:@"Authorization"];
    
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    if (connection) {
        responseData = [[NSMutableData alloc] init];
    }
    
}

-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    [scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x, 0)
                        animated:NO];
    
    if([segue.identifier isEqualToString:@"ToComplain"])
    {
        ComplainViewController*p = (ComplainViewController*)segue.destinationViewController;
        p.authenKey = authorizationData;
        p.currentType = currentType;
        p.currentCom0Type = currentL0;
        //[p clearData];
    }
    if([segue.identifier isEqualToString:@"ToEditUser"])
    {
        NSLog(@"test");
        //self.navigationController.navigationBar.topItem.title = @"เเก้ไขข้อมูลสมาชิก";
        RegisterViewController *r = (RegisterViewController*)segue.destinationViewController;
        r.userInfo = userInfo;
        r.mode = @"edit";
        r.authorizationData = authorizationData;
        
        r.userInfo_nameText = nameText;
        r.userInfo_telText = telText;
        r.userInfo_emailText = emailText;
        r.userInfo_address = address;
        
    }
    if ([segue.identifier isEqualToString:@"userInfoToKeepTrack"])
    {
        KeepTrackViewController *k = (KeepTrackViewController*)segue.destinationViewController;
        k.authorizationData = [[NSString alloc] initWithString:authorizationData];
    }
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSError *error = nil;
    //NSString *jsonResponse =  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSDictionary* jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    
    NSString* error_code = [jsonObject valueForKey:@"error_code"];
    
    
    NSString *jsonRequest =  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSLog(@"jsonResponse is %@", jsonRequest);
    
    if(error_code.intValue > 0)
    {
        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"OCPB!"
                                                          message:[jsonObject valueForKey:@"message"]
                                                         delegate:nil
                                                cancelButtonTitle:@"OK"
                                                otherButtonTitles:nil];
        [message show];
        
    }
    else
    {
        //Aumphur* aumphur = [[Aumphur alloc] init];
        userInfo = [[UserInfo alloc] init];
        
        for(NSString *item in [jsonObject allKeys]) {
            
            if([item isEqual: @"data"] )
            {
                NSDictionary *userInfoJSON = [jsonObject valueForKey:item];
                
                /*
                 @"Petitioner_password"
                 @"Petitioner_FName"
                 @"Petitioner_LName"
                 @"Petitioner_IDCard"
                 @"Petitioner_Username"
                 @"Tumbol_id"
                 @"Amphur_id"
                 @"Province_id"
                 @"PostCode"
                 @"Petitioner_mobile"
                 @"Petitioner_mail"
                 */
                
                if (![[userInfoJSON valueForKey:@"Petitioner_password"] isKindOfClass:[NSNull class]])
                {
                    userInfo.password = (NSString *)[userInfoJSON valueForKey:@"Petitioner_password"];
                }
                if (![[userInfoJSON valueForKey:@"Petitioner_FName"] isKindOfClass:[NSNull class]])
                {
                    userInfo.fName = (NSString *)[userInfoJSON valueForKey:@"Petitioner_FName"];
                }
                if (![[userInfoJSON valueForKey:@"Petitioner_LName"] isKindOfClass:[NSNull class]])
                {
                    userInfo.lName = (NSString *)[userInfoJSON valueForKey:@"Petitioner_LName"];
                    nameText.text = [NSString stringWithFormat: @"%@ %@", userInfo.fName, userInfo.lName];
                    [nameText setEnabled:NO];
                }
                if (![[userInfoJSON valueForKey:@"Petitioner_IDCard"] isKindOfClass:[NSNull class]])
                {
                    userInfo.idNumber = (NSString *)[userInfoJSON valueForKey:@"Petitioner_IDCard"];
                    idNumberText.text = [userInfoJSON valueForKey:@"Petitioner_IDCard"];
                    [idNumberText setEnabled:NO];
                }
                if (![[userInfoJSON valueForKey:@"Petitioner_Username"] isKindOfClass:[NSNull class]])
                {
                    userInfo.username = (NSString *)[userInfoJSON valueForKey:@"Petitioner_Username"];
                }
                if (![[userInfoJSON valueForKey:@"Tumbol_id"] isKindOfClass:[NSNull class]])
                {
                    userInfo.tumbol_id = (NSString *)[userInfoJSON valueForKey:@"Tumbol_id"];
                }
                if (![[userInfoJSON valueForKey:@"Amphur_id"] isKindOfClass:[NSNull class]])
                {
                    userInfo.amphur_id = (NSString *)[userInfoJSON valueForKey:@"Amphur_id"];
                }
                if (![[userInfoJSON valueForKey:@"Province_id"] isKindOfClass:[NSNull class]])
                {
                    userInfo.province_id = (NSString *)[userInfoJSON valueForKey:@"Province_id"];
                }
                if (![[userInfoJSON valueForKey:@"PostCode"] isKindOfClass:[NSNull class]])
                {
                    userInfo.postCode = (NSString *)[userInfoJSON valueForKey:@"PostCode"];
                }
                if (![[userInfoJSON valueForKey:@"Petitioner_mobile"] isKindOfClass:[NSNull class]])
                {
                    userInfo.mobile = (NSString *)[userInfoJSON valueForKey:@"Petitioner_mobile"];
                    telText.text = [userInfoJSON valueForKey:@"Petitioner_mobile"];
                    [telText setEnabled:NO];
                }
                if (![[userInfoJSON valueForKey:@"Petitioner_mail"] isKindOfClass:[NSNull class]])
                {
                    userInfo.email = (NSString *)[userInfoJSON valueForKey:@"Petitioner_mail"];
                    emailText.text = [userInfoJSON valueForKey:@"Petitioner_mail"];
                    [emailText setEnabled:NO];
                }
                if (![[userInfoJSON valueForKey:@"Address"] isKindOfClass:[NSNull class]])
                {
                    userInfo.address = (NSString *)[userInfoJSON valueForKey:@"Address"];
                    address.text = (NSString *)[userInfoJSON valueForKey:@"Address"];
                    [address setEditable:NO];
                }
                
                
                /*
                for(NSDictionary *dara in allDara )
                {
                    Province* province = [[Province alloc] init];
                    province.prov_code = [dara valueForKey:@"Prov_code"];
                    province.prov_thai = [dara valueForKey:@"Prov_nameT"];
                    province.prov_eng = [dara valueForKey:@"prov_nameE"];
                    
                    [provinceArray addObject:province];
                }
                */
            }
        }
    }
}
- (IBAction)ClickComplain:(id)sender {
    
    [self load_comLv0];
    mainAlert = [[UIAlertView alloc] initWithTitle:@"เลือกเรื่องร้องทุกข์"
                                           message:@""
                                          delegate:self
                                 cancelButtonTitle:@"ยกเลิก"
                                 otherButtonTitles:nil];
    
    for( ComTypeLv0 *item in comTypeLv0Array) {
        [mainAlert addButtonWithTitle:item.name];
        
    }
    
    [mainAlert show];
}

-(void) load_comLv0
{
    comTypeLv0Array = [[NSMutableArray alloc] init];
    
    NSDictionary *publicTimeline =  jsonObjectFromUrlString(@"http://www.aitproject.com/demo/webservice/public/service/complain-type?type=lv0");
    
    
    for(NSString *item in [publicTimeline allKeys]) {
        
        if([item isEqual: @"data"] )
        {
            NSDictionary *allData = [publicTimeline valueForKey:item];
            
            NSArray *allSue = [allData valueForKey:item];
            
            for(NSDictionary *data in allSue )
            {
                
                ComTypeLv0* comLv0 = [[ComTypeLv0 alloc] init];
                comLv0.type_id = [data valueForKey:@"Complain_Type_Id"];
                comLv0.level = [data valueForKey:@"Complain_Type_Level"];
                comLv0.refer = [data valueForKey:@"Complain_Type_Refer"];
                comLv0.name = [data valueForKey:@"Complain_Type_Name"];
                
                [comTypeLv0Array addObject:comLv0];
                
            }
            
        }
    }
    
    //currentComLv0 = comTypeLv0Array[[currentType intValue]];
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView == mainAlert)
    {
         if(buttonIndex == 0)
         {
            return;
         }
         else if(buttonIndex == 1)
         {
             currentType = @"0";
         }
         else if(buttonIndex == 2)
         {
             currentType = @"1";
         }
         else if(buttonIndex == 3)
         {
             currentType = @"2";
         }
        
         //ComTypeLv0* comLv0 = comTypeLv0Array[buttonIndex - 1];

        
        //currentType = comLv0.type_id;
        
        
        //currentType = [NSString stringWithFormat:@"%d",buttonIndex];
        currentL0 = [NSString stringWithFormat:@"0"];
        
        [self performSegueWithIdentifier:@"ToComplain" sender:self];

        
        //[self load_comLv0];
        
       // typeAlert = [[UIAlertView alloc] initWithTitle:@"เลือกประเภทหลัก"
//                                               message:@""
//                                              delegate:self
//                                     cancelButtonTitle:@"ยกเลิก"
//                                     otherButtonTitles:nil];
//        
//        for( ComTypeLv0 *item in comTypeLv0Array) {
//            [typeAlert addButtonWithTitle:item.name];
        
  //      }
        
 //       [typeAlert show];
    }
    else
    {
        if(buttonIndex == 0)
        {
            return;
        }
        
        currentL0 = [NSString stringWithFormat:@"%d",buttonIndex - 1];
        
        [self performSegueWithIdentifier:@"ToComplain" sender:self];
    }
    
}
@end
